package com.itheima.ydd.controller;

import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.YddUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ydd_user")
public class YddUserController {
    @Autowired
    private YddUserService yddUserService;

    /**
     * 修改用户 -- 回显数据
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(Integer id){
        log.info("修改用户id: {}",id);
        YddUser yddUser = yddUserService.getById(id);
        return ResultData.ok(null,yddUser);
    }

    /**
     * 用户分页条件查询
     * @param sex
     * @param username
     * @param mobile
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(Integer sex, String username, String mobile, Long page, Long limit){
        log.info("分页查询条件: sex:{}, username:{}, mobile:{}, page:{}, limit:{}",sex,username,mobile,page,limit);
        PageResult pageResult = yddUserService.getList(sex,username,mobile,page,limit);
        return ResultData.ok("",pageResult);
    }

    /**
     * 添加用户
     * @param yddUser
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddUser yddUser){
        log.info("添加用户信息: {}",yddUser);
        //将密码进行md5加密处理
        String password = yddUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        yddUser.setPassword(password);
        yddUserService.save(yddUser);
        log.info(yddUser.getId()+"");
        return ResultData.ok("添加成功",null);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(Integer id){
        log.info("删除用户id: {}",id);
        yddUserService.removeById(id);
        return ResultData.ok("删除成功",null);
    }

    /**
     * 用户修改
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddUser yddUser){
        log.info("修改用户数据: {}",yddUser);
        //将密码进行md5加密处理
        String password = yddUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        yddUser.setPassword(password);
        yddUserService.updateById(yddUser);
        return ResultData.ok("修改成功",null);
    }
}
